package com.showsu.editor.exception;

import com.showsu.editor.enums.ResultCode;
import com.showsu.editor.session.SessionException;
import com.showsu.editor.utils.BsResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author pizhiyong
 * @create 2021-05-21 10:47:25
 *
 * 使用@RestControllerAdvice开启全局异常捕获
 * 在指定方法上使用@ExceptionHandler
 * 用于捕获Controller中抛出的不同类型的异常；
 * 异常处理
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
 
    /**
     * 会话异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = SessionException.class)
    @ResponseBody
    public BsResult tokenExpiredException(HttpServletRequest req, SessionException e){
        log.info("登录过期-请重新登录:{}");
        return BsResult.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理自定义的业务异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public BsResult bizExceptionHandler(HttpServletRequest req, BizException e){
        log.error("发生业务异常！原因是:{}",e.getErrorMsg());
        return BsResult.error(e.getErrorCode(), e.getErrorMsg());
    }

    /**
     * 处理空指针的异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public BsResult exceptionHandler(HttpServletRequest req, NullPointerException e){
        log.error("发生空指针异常！原因是:{}", e);
        return BsResult.error(ResultCode.NOT_FOUND);
    }


    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public BsResult exceptionHandler(HttpServletRequest req, Exception e){
        log.error("未知异常！原因是:{}",e);
        return BsResult.error(ResultCode.INTERNAL_SERVER_ERROR);
    }

}
